package cn.iocoder.yudao.module.mqtt.util;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class MyFileUtil {

    public static void saveFile(MultipartFile file, String filePath) {
        // 检查文件是否为空
        if (file.isEmpty()) {
            throw new IllegalArgumentException("文件不能为空");
        }
        // 创建目标文件对象
        File destFile = new File(filePath);
        // 确保目标文件的父目录存在
        destFile.getParentFile().mkdirs();

        try (InputStream inputStream = file.getInputStream();
             FileOutputStream outputStream = new FileOutputStream(destFile)) {
            // 读取输入流并写入输出流
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            System.out.println("文件已成功保存到：" + filePath);
        } catch (IOException e) {
            throw new RuntimeException("保存文件时发生错误", e);
        }
    }

    public static String getClientIpAddress(HttpServletRequest request) {
        // 获取 X-Forwarded-For 头部，这通常包含原始客户端 IP
        String ipAddress = request.getHeader("X-Forwarded-For");

        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            // 如果 X-Forwarded-For 不存在，尝试获取 Proxy-Client-IP
            ipAddress = request.getHeader("Proxy-Client-IP");
        }

        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            // 如果 Proxy-Client-IP 不存在，尝试获取 WL-Proxy-Client-IP
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }

        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            // 如果上述头部都不存在，使用 request.getRemoteAddr()
            ipAddress = request.getRemoteAddr();
        }

        // 如果 X-Forwarded-For 存在，取第一个 IP 地址
        if (ipAddress != null && ipAddress.contains(",")) {
            ipAddress = ipAddress.split(",")[0].trim();
        }

        return ipAddress;
    }
}
